/*!
 * Ext JS Library 3.3.1
 * Copyright(c) 2006-2010 Sencha Inc.
 * licensing@sencha.com
 * http://www.sencha.com/license
 */
QueuedReferenceWindow = Ext.extend(Ext.app.Module, {
    id: 'qref-win',
    autostart: true,
    store: null,
    init: function() {
        this.launcher = {
            text: 'Queued References',
            iconCls: 'refwin-icon',
            handler: this.createWindow,
            scope: this
        };
    },
    
    checkForUpdate: function() {
    	var ref = this;
    	window.setTimeout(function() {
    		ref.store.reload();
    		ref.checkForUpdate();
    	}, 5000);
    	/*
    	Ext.Ajax.request({
			loadMask: true,
			url: 'references',
			params: {
				'action': 'expectQueuedReferencesUpdate'
			},
			success: function(resp) {
				ref.store.reload();
				ref.checkForUpdate();
			},
			failure: function() {
				ref.checkForUpdate();
			}
		});*/
    },

     createWindow: function() {
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('qref-win');
        
        // create the data store
        var store = new Ext.data.JsonStore({
        	autoDestroy: true,
        	totalProperty: 'results',
        	root: 'rows',
        	url: './references?action=getQueuedReferences',
        	fields: ['refuri', 'refxpath']
        });
        store.on('load', function() {
        	if (store.getTotalCount() > 0) {
        		win.show();
        	} else {
        		win.hide();
        	}
        });
        this.store = store;

        // create the Grid
        var grid = new Ext.grid.GridPanel({
            store: store,
            columns: [          
                {
                    id       :'refuri',
                    header   : 'URI',
                    width    : 200,
                    sortable : true,
                    dataIndex: 'refuri'
                },
                {
                    id		 : 'refxpath',
                    header   : 'XPath',
                    width    : 150,
                    sortable : true,
                    dataIndex: 'refxpath' 
                }           
            ],
            stripeRows: true,
            title: 'Queued References',
            // config options for stateful behavior
            stateful: true,
            stateId: 'grid'
        });
       
        grid.on('render', function() {
        	
            grid.dropZone = new Ext.dd.DropZone(grid.getView().scroller, {

//              If the mouse is over a grid row, return that node. This is
//              provided as the "target" parameter in all "onNodeXXXX" node event handling functions
                getTargetFromEvent: function(e) {
                    return e.getTarget(grid.getView().rowSelector);
                },

//              On entry into a target node, highlight that node.
                onNodeEnter : function(target, dd, e, data){ 
                    Ext.fly(target).addClass('my-row-highlight-class');
                },

//              On exit from a target node, unhighlight that node.
                onNodeOut : function(target, dd, e, data){ 
                    Ext.fly(target).removeClass('my-row-highlight-class');
                },

//              While over a target node, return the default drop allowed class which
//              places a "tick" icon into the drag proxy.
                onNodeOver : function(target, dd, e, data){ 
                    return Ext.dd.DropZone.prototype.dropAllowed;
                },

//              On node drop we can interrogate the target to find the underlying
//              application object that is the real target of the dragged data.
//              In this case, it is a Record in the GridPanel's Store.
//              We can use the data set up by the DragZone's getDragData method to read
//              any data we decided to attach in the DragZone's getDragData method.
                onNodeDrop : function(target, dd, e, data){
                    var rowIndex = grid.getView().findRowIndex(target);
                    
                    grid.getSelectionModel().selectRow(rowIndex);
                	var row = grid.getStore().getAt(rowIndex);
                	var url = row.data.refuri;
                	var xpath = row.data.refxpath;
                	ReferenceManager.addReference(url, xpath, data.url, data.section, function() {
                		//Ext.Msg.alert('Add Reference', 'Reference saved successfully.');
	        			store.reload();
	        			Ext.ComponentMgr.get('mydesktop').getModule('ref-win').reloadReferences(null);
	        		});
                    return true;
                }
            });
        });
        grid.addListener('rowdblclick', function(grid, rowIndex, e) {
        	e.stopEvent(); 
        	grid.getSelectionModel().selectRow(rowIndex);
        	var row = grid.getStore().getAt(rowIndex);
        	var url = row.data.refuri;
        	var xpath = row.data.refxpath;
        	var title = url.substr(url.indexOf("://")+3);
        	title = title.substr(0, title.indexOf("/"));
        	MyDesktop.getModule('browser-win').createWindow(title, url, xpath);
        	//alert('TODO: Open URL in new Browser: ' + url);
        });
        grid.addListener('rowcontextmenu', function(grid, rowIndex, e) {
        	e.stopEvent(); 
        	grid.getSelectionModel().selectRow(rowIndex); 
        	var row = grid.getStore().getAt(rowIndex);
        	var coords = e.getXY(); 
        	var items = new Array();
        	var url = row.data.refuri;
        	var xpath = row.data.refxpath;
        	var slideuri = Ext.getDom('slideview').src;
              
        	items.push({text: 'Discard', handler: function() {
        		ReferenceManager.discardQueuedReference(url, xpath, function(success) {
        			store.reload();
        		});
        	}});
        
        	if (slideuri) {
	        	items.push({text: 'Link with current slide', handler: function() {
	        		ReferenceManager.addReference(url, xpath, slideuri, "", function() {
	        			store.reload();
	        			Ext.ComponentMgr.get('mydesktop').getModule('ref-win').reloadReferences(null);
	        			Ext.ComponentMgr.get('mydesktop').getModule('graph-win').reloadGraph();
	        		});
	        	}});
        	}
        	var subItems = new Array();
        	var i = 1;
        	grid.getStore().each(function(rec) {
        		if (!(rec.get('refuri') == url && xpath == rec.get('refxpath'))) {
	        		var recUrl = rec.get('refuri');
	        		var recXpath = rec.get('refxpath');
	            	var title = recUrl.substr(recUrl.indexOf("://")+3);
	            	title = title.substr(0, title.indexOf("/"));
	        		subItems.push({text: i + ': '+ title, handler: function() {
	        			ReferenceManager.addReference(url, xpath, recUrl, recXpath, function() {
		        			store.reload();
		        			Ext.ComponentMgr.get('mydesktop').getModule('ref-win').reloadReferences(null);
		        			Ext.ComponentMgr.get('mydesktop').getModule('graph-win').reloadGraph();
		        		});
	        		}});
        		}
        		i++;
        	});
        	if (i > 2) {
        		items.push({text: 'Link with...', menu: subItems});
        	}
        	var menu = new Ext.menu.Menu({
                items: items
            });
            menu.showAt([coords[0], coords[1]]); 
        });
        store.load();
        
        if (!win) {
            win = desktop.createWindow({
                id: 'qref-win',
                title: 'Queued Reference Window',
                width: 500,
                height: 250,
                x: 340,
                y: 400,
                iconCls: 'refwin-icon',
                shim: false,
                animCollapse: false,
                border: false,
                constrainHeader: true,
                collapsible: true,
                layout: 'fit',
                items: [ grid ]
            });
        }
        //win.show();
        this.checkForUpdate();
     }
});